<?php

namespace App\Services;

use App\Common\Enums\AdvClickSourceEnum;
use App\Common\Enums\ConvertCallbackCountByEnum;
use App\Common\Enums\ConvertCallbackTimeEnum;
use App\Common\Enums\ConvertTypeEnum;
use App\Common\Helpers\Functions;
use App\Common\Models\ClickModel;
use App\Common\Models\ConvertCallbackModel;
use App\Common\Models\ConvertCallbackStrategyModel;
use App\Common\Services\ConvertMatchService;
use App\Models\Ocean\OceanPromotionExtendModel;
use App\Models\Ocean\OceanPromotionModel;

//use App\Models\Ocean\OceanAdExtendModel;

class AdvConvertMatchService extends ConvertMatchService
{
    /**
     * @var
     */
    public $strategyStartAt;

    /**
     * @var string
     * 计划id字段
     */
    public $adIdField = 'promotion_id';

    /**
     * @param $click
     * @param $convert
     * @return array|mixed|void
     * @throws \App\Common\Tools\CustomException
     * 获取转化回传规则
     */
    protected function getConvertCallbackStrategy($click, $convert){
        // 转化类型
        $convertType = $convert['convert_type'];

        $strategy = null;
        $defaultStrategyId = env('APP_DEFAULT_STRATEGY_ID', 0);
        if(!empty($defaultStrategyId)){
            $convertCallbackStrategyModel = new ConvertCallbackStrategyModel();
            $convertCallbackStrategy = $convertCallbackStrategyModel->where('id', $defaultStrategyId)->first();
            if(!empty($convertCallbackStrategy)){
                $strategy = $convertCallbackStrategy['extends'];
            }
        }

        if(empty($strategy)){
            // 默认策略
            $strategy = [
                ConvertTypeEnum::REGISTER => [
                    'time_range' => ConvertCallbackTimeEnum::TODAY,
                    'convert_times' => 1,
                    'callback_rate' => 100,
                ],
                ConvertTypeEnum::PAY => [
                    'time_range' => ConvertCallbackTimeEnum::TODAY,
                    'convert_times' => 1,
                    'callback_rate' => 100,
                    'min_amount'    => 29,
//                    'must_callback_count' => 6,
                    'convert_callback_count_by' => ConvertCallbackCountByEnum::BY_AD_ID,
                    'convert_cost' => 400,
                    'bid_ratio' => 1.2,
                ],
            ];
        }

        // 配置策略
        $promotionId = $click->promotion_id ?? 0;
        $promotionExtend = OceanPromotionExtendModel::find($promotionId);
        if(!empty($promotionExtend) && !empty($promotionExtend->convert_callback_strategy()->enable()->first())){
            $strategy = $promotionExtend->convert_callback_strategy['extends'];
        }

        // 配置策略组
        if(!empty($promotionExtend) && !empty($promotionExtend->convert_callback_strategy_group()->enable()->first())){
            $strategy = $this->getStrategyByGroup($promotionExtend->convert_callback_strategy_group['extends']['config'], $convert) ?? $strategy;
        }

        if(!empty($promotionExtend)){
            $pe = $promotionExtend->toArray();
            $this->strategyStartAt = $pe['updated_at'];
        }

        return $strategy[$convertType] ?? ['time_range' => ConvertCallbackTimeEnum::NEVER];

    }

    /**
     * @param $click
     * @param $convert
     * @return mixed
     * 获取转化回传列表
     */
    protected function getConvertCallbacks($click, $convert){
        $clickDatetime = date('Y-m-d H:i:s', strtotime("-15 days", strtotime($convert['convert_at'])));
        $clickDate = [date('Y-m-d', strtotime($clickDatetime)), date('Y-m-d', strtotime($convert['convert_at']))];
        $convertDate = date('Y-m-d', strtotime($convert['convert_at']));
        $convertRange = [
            $convertDate .' 00:00:00',
            $convertDate .' 23:59:59',
        ];

        $promotionId = $click->promotion_id ?? 0;

        $convertCallbackModel = new ConvertCallbackModel();
        $builder = $convertCallbackModel->whereRaw("
            click_id IN (
                SELECT id FROM clicks
                    WHERE promotion_id = '{$promotionId}'
                        AND click_at BETWEEN '{$clickDatetime}' AND '{$convert['convert_at']}'
                        AND click_date BETWEEN '{$clickDate[0]}' AND '{$clickDate[1]}'
            ) AND convert_at BETWEEN '{$convertRange[0]}' AND '{$convertRange[1]}'
            AND convert_type IN ('{$convert['convert_type']}')
        ");

        if(!empty($this->strategyStartAt)){
            $builder->where('convert_at', '>=', $this->strategyStartAt);
        }

        $convertCallbacks = $builder->get();

        return $convertCallbacks;
    }

    /**
     * @param $data
     * @return ClickModel|void
     * 获取匹配查询构造器
     */
    protected function getMatchByBuilder($data){
        $builder = new ClickModel();

        $isTransfer = in_array( AdvClickSourceEnum::N8_TRANSFER, $this->clickSource) && count($this->clickSource) == 1;
        if(!$isTransfer){
            $channelId = $data['n8_union_user']['channel_id'] ?? 0;
            if(!empty($channelId)){
                $builder = $builder->whereRaw("
                    channel_id = {$channelId}
                ");
            }
        }

        return $builder;
    }

    /**
     * @param $click
     * @param $convert
     * @return mixed
     * 获取计划转化统计
     */
    protected function getAdConvertStat($click, $convert){
        $promotionId = $click->promotion_id ?? '';
        if(Functions::isLocal() && $promotionId == '7342888172856672283'){
            $promotionId = '7348798619103920167';
        }

        $promotionConvertService = new PromotionConvertService();
        $item = $promotionConvertService->getPromotionConvertStat($promotionId);
        return $item;
    }

    /**
     * @param $click
     * @param $convert
     * @return mixed
     * 获取计划
     */
    protected function getAd($click, $convert){
        $promotionId = $click->promotion_id ?? '';
        $oceanPromotionModel = new OceanPromotionModel();
        $oceanPromotion = $oceanPromotionModel->where('id', $promotionId)->first();
        return $oceanPromotion;
    }
}
